from concurrent.futures import ThreadPoolExecutor

from drf_spectacular.utils import extend_schema
from rest_framework import viewsets

from .models import Case
from .serializers import UICaseSerializer

pool = ThreadPoolExecutor(max_workers=6)


@extend_schema(tags=["UICase"])
class CaseViewSets(viewsets.ModelViewSet):
    queryset = Case.objects.all()  # 数据来源
    serializer_class = UICaseSerializer  # 数据格式

    # @action(methods=["POST"], detail=True)  # 选定某一条用例进行执行
    # def generate_and_run_excel_case(
    #         self, request: Request, pk
    # ):  # self表示的是数据库中id为pk的那条数据记录
    #     """调试接口,临时运行测试框架"""
    #     obj: Case = self.get_object()  # 得到用例的对象
    #     # 生成的yaml用例存放在什么地方
    #     path = Path("suite_cases") / f"case_{pk}_{time.time()}_{uuid.uuid4()}"
    #     # 创建目录
    #     Path.mkdir(path, parents=True, exist_ok=True)
    #
    #     # 生成用例文件
    #     obj.save_excel(path)
    #
    #     run_result = RunResult.objects.create(
    #         path=path
    #     )  # 存放执行的结果(只需要提供用例的路径即可)
    #     # 多线程调用子进程执行用例
    #     pool.submit(start_frame, path, run_result)
    #
    #     return Response(
    #         {
    #             "code": 0,
    #             "msg": "xlsx文件生成成功,需要查看结果请调用用例结果查询接口,id传递result_id的值",
    #             "result_id": run_result.id,
    #         }
    #     )
